#ifndef __MY_SERVER__
#define __MY_SERVER__
#include "httplib.h"
#include "data.hpp"

namespace aod
{
#define WWW_ROOT "./www"
#define VIDEO_ROOT "/video/"
#define IMAGE_ROOT "/image/"
    // 因为httplib基于多线程，因此数据管理对象需要在多线程中访问，为了方便访问定义全局变量
    aod::TableVideo *tb_video = NULL; // 找到源头了
    // 为了令功能模块更加清晰，不适用lamda表达式完成，否则所有的功能实现集中到一个函数中太过庞大
    class Server
    {
    private:
        int _port;            // 服务器的监听端口
        httplib::Server _svr; // 用于搭建http服务器
    private:
        // 对应的业务接口
        static void Insert(const httplib::Request &req, httplib::Response &rsp)
        {
            if (req.has_file("name") == false ||
                req.has_file("info") == false ||
                req.has_file("video") == false ||
                req.has_file("image") == false)
            {
                rsp.status = 400;
                rsp.body = R"({"result":false,"reason":"上传的数据信息错误"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }

            httplib::MultipartFormData name = req.get_file_value("name");   // 视频名称
            httplib::MultipartFormData info = req.get_file_value("info");   // 视频简介
            httplib::MultipartFormData video = req.get_file_value("video"); // 视频文件
            httplib::MultipartFormData image = req.get_file_value("image"); // 图片文件

            std::string video_name = name.content;
            std::string video_info = info.content;
            //
            std::string root = WWW_ROOT;
            std::string video_path = root + VIDEO_ROOT + video_name + video.filename;
            std::string image_path = root + IMAGE_ROOT + video_name + image.filename;

            if (FileUtil(video_path).SetContent(video.content) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false , "reason":"视频文件存储失败"})";
                rsp.set_header("Content-Type", "application/json");
            }
            if (FileUtil(image_path).SetContent(image.content) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false , "reason":"图片文件存储失败"})";
                rsp.set_header("Content-Type", "application/json");
            }

            Json::Value video_json;
            video_json["name"] = video_name;
            video_json["info"] = video_info;
            video_json["video"] = std::string(VIDEO_ROOT) + video_name + video.filename; //
            video_json["image"] = std::string(IMAGE_ROOT) + video_name + image.filename; //

            // std::cout<< video_json["name"] <<std::endl;
            // std::cout<< video_json["info"] <<std::endl;
            // std::cout<< video_json["video"] <<std::endl;
            // std::cout<< video_json["image"] <<std::endl;

            // 下方有错误
            // bool test = tb_video->Insert(video_json);

            if (tb_video->Insert(video_json) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false , "reason":"数据库新增数据失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
                rsp.set_redirect("/index.html",303);
            return;
        }

        static void Update(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1. 获取要修改的视频信息 1. 视频id 2.修改后的信息
            int video_id = std::stoi(req.matches[1]);
            Json::Value video;
            if (JsonUtil::UnSerialize(req.body, &video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"新的视频信息格式解析失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            // 2.修改数据库数据
            if (tb_video->Update(video_id, video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"修改数据库信息失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            return;
        }

        static void Delete(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1.获取要删除的视频ID
            int video_id = std::stoi(req.matches[1]);
            // 2.删除视频以及图片文件
            Json::Value video;
            if (tb_video->SelectOne(video_id, &video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"不存在视频信息"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            std::string root;
            std::string video_path = root + video["video"].asString();
            std::string image_path = root + video["video"].asString();
            remove(video_path.c_str());
            remove(image_path.c_str());
            // 4.删除数据库信息
            if (tb_video->Delete(video_id) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"删除数据库信息失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            return;
        }

        static void SelectOne(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1.获取新的视频信息
            int video_id = std::stoi(req.matches[1]);
            // 2.在数据库中查询指定视频信息
            Json::Value video;
            if (tb_video->SelectOne(video_id, &video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"查询数据库指定视频信息失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            // 3.组织响应正文 -- json格式的字符串
            JsonUtil::Serialize(video, &rsp.body);
            rsp.set_header("Content-Type", "application/json");
            return;
        }

        static void SelectAll(const httplib::Request &req, httplib::Response &rsp)
        {
            // /video  &   /video?search="关键字"
            bool select_flag = true; // 默认所有查询
            std::string search_key;
            if (req.has_param("search") == true)
            {
                select_flag = false; // 模糊匹配
                search_key = req.get_param_value("search");
                // std::cout<< search_key << std::endl;
            }
            Json::Value videos;
            if (select_flag == true)
            {
                if (tb_video->SelectAll(&videos) == false)
                {
                    rsp.status = 500;
                    rsp.body = R"({"result":false, "reason":"查询数据库所有视频信息失败"})";
                    rsp.set_header("Content-Type", "application/json");
                    return;
                }
            }
            else
            {
                if (tb_video->SelectLike(search_key, &videos) == false)
                {
                    rsp.status = 500;
                    rsp.body = R"({"result":false, "reason":"查询数据库匹配视频信息失败"})";
                    rsp.set_header("Content-Type", "application/json");
                    return;
                }
            }
            JsonUtil::Serialize(videos, &rsp.body); //
            rsp.set_header("Content-type", "application/json");
        }

    public:
        Server(int port) : _port(port) {}
        bool RunModule() // 建立请求与处理函数的映射关系，设置静态资源根目录，启动服务器
        {
            // TableVideo* tb_video = new TableVideo; //这里是局部变量 下面的是全局变量
            tb_video = new TableVideo; // 静态 or 动态？？ 过多的变量放到栈容易溢出
            // std::cout<< tb_video << std::endl;
            FileUtil(WWW_ROOT).CreateDirectory();
            std::string root = WWW_ROOT;
            std::string video_real_path = root + VIDEO_ROOT; // ./www/video/
            FileUtil(video_real_path).CreateDirectory();
            std::string image_real_path = root + IMAGE_ROOT; // ./www/image/
            FileUtil(image_real_path).CreateDirectory();
            // 2. 搭建http服务器，开始运行
            //  1.设置静态资源根目录
            _svr.set_mount_point("/", WWW_ROOT);
            // 2.添加请求-处理函数映射关系
            _svr.Post("/video", Insert);
            _svr.Delete("/video/(\\d+)", Delete);
            _svr.Put("/video/(\\d+)", Update);
            _svr.Get("/video/(\\d+)", SelectOne);
            _svr.Get("/video", SelectAll);
            // 3.启动服务器
            // std::cout << "ready to listen " <<std::endl;
            _svr.listen("0.0.0.0", _port);
            // std::cout << "listen success" << std::endl;

            return true;
        }
    };

}
#endif